var user_WebHosting = function() {

    var serviceUploadedFiles = [];

    var serviceTableLength, newService, servicename4Upload, location4Upload, servicename4Quota, location4Quota;

    //$(document).ready(function() {
    serviceTableLength = $('#userWebHostingInfoTable').dataTable()[0].rows.length;

    function userWebHostingLoadInfoTable() {
        var currentuser;
        $('#userWebHostingInfoTable').dataTable().fnClearTable();
        // $.post('/app/whoiam', {},
        //function(serverResponse) {
        currentuser = userid; //serverResponse.userid;
        for (var j = 0; j < allsites.length; j += 1) { (function(siteName) {
                $.post('/' + siteName + '/webhosting/execute_wait/webapi.serviceTableByUser.json', {
                    userName: currentuser
                },
                function(serverResponse) {
                    var servicename;
                    var servicetype;
                    var webftp;
                    var php;
                    var mysql;

                    for (var i = 0; i < serverResponse.length; i += 1) {
                        servicename = serverResponse[i].serviceName;
                        servicetype = serverResponse[i].serviceType;
                        webftp = serverResponse[i].webftp;
                        php = serverResponse[i].phpMyAdmin;
                        mysql = serverResponse[i].mysql;
                        $('#userWebHostingInfoTable').dataTable().fnAddData([
                        siteName, servicename, servicetype, webftp, php, mysql]);
                        //console.log(serverResponse);
                        //console.log(serverResponse.length );
                        //  console.log(tnc );
                        //  console.log(inputfile );
                        //  console.log(command );
                        //  console.log(state );
                        //  console.log(result );
                    }
                },
                'json');
            })(allsites[j]);
        }
        // },
        // 'json');
    };

    $('#userWebHostingServiceDeleteButton').click(function() {
        var anSelected = fnGetSelected(userWebHostingInfoTable);
        var a = $('td', anSelected);
        if (a.length == 0) {
            alert("please select one row!");
            return 0;
        }

        var location = $(a[0]).text();
        var servicename = $(a[1]).text();

        $("#craneModalDialogContent").text("Are you sure to delete this service?Service_Name:" + servicename);
        $('#craneModalDialog').dialog({
            buttons: {
                Confirm: function() {
                    $(this).dialog('close');
                    $.post('/' + location + '/webhosting/execute_wait/webapi.deleteService.json', {
                        serviceName: servicename
                    },
                    function(serverResponse) {
                        if (serverResponse == null) {

                            alert("Delete failed!");
                            return 0;

                        }
                        else {
                            userWebHostingInfoTable.fnDeleteRow(anSelected[0]);
                            serviceTableLength -= 1;
                        }
                    },
                    'json');
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        }).dialog('open');

    });

    $('#userWebHostingServiceDetailDialog').dialog({
        width: 250,
        autoOpen: false,
        modal: true,
        title: 'Service Quota',
        buttons: {

            OK: function() {
                $(this).dialog("close");
            },
            Refresh: function() {
                var webuse, dbuse, webtotal, dbtotal, webusage, dbusage;
                var webindicator = document.getElementById("userWebHostingWebStorageCapacityIndicator");
                var dbindicator = document.getElementById("userWebHostingDBStorageCapacityIndicator");

                $("#userWebHostingWebStorageCapacityField")[0].value = 0;
                $("#userWebHostingWebStorageUsedField")[0].value = 0;
                webindicator.object.setValue(0);
                $("#userWebHostingDBStorageCapacityField")[0].value = 0;
                $("#userWebHostingDBStorageUsedField")[0].value = 0;
                dbindicator.object.setValue(0);

                $.post('/' + location4Quota + '/webhosting/execute_wait/webapi.queryQuotaByService.json', {
                    serviceName: servicename4Quota
                },
                function(serverResponse) {
                    if (serverResponse == null) {
                        alert("No Quota!");
                    }

                    else {
                        webuse = serverResponse.webuse;
                        dbuse = serverResponse.dbuse;
                        webtotal = serverResponse.webtotal;
                        dbtotal = serverResponse.dbtotal;
                        webusage = serverResponse.webrate;
                        dbusage = serverResponse.dbrate;
                        //console.log(webusage);
                        //console.log(dbusage);
                        $("#userWebHostingWebStorageCapacityField")[0].value = webuse;
                        $("#userWebHostingWebStorageUsedField")[0].value = webtotal;
                        webindicator.object.setValue(webusage);
                        $("#userWebHostingDBStorageCapacityField")[0].value = dbtotal;
                        $("#userWebHostingDBStorageUsedField")[0].value = dbuse;
                        dbindicator.object.setValue(dbusage);
                    }
                },
                'json');
            }
        }
    });

    $('#userWebHostingAddServiceDialog').dialog({
        width: 250,
        autoOpen: false,
        modal: true,
        title: 'Create Web　Service',
        buttons: {
            Confirm: function() {
                var servicename = $("#userWebHostingServiceNameField")[0].value;
                var type = $("#userWebHostingServiceTypeField")[0].value;
                var pwd = $("#userWebHostingPasswordField")[0].value;
                var pwd2 = $("#userWebHostingPasswordConfirmField")[0].value;
                var typenum;
                var sitename = $("#preferredSiteComboBox")[0].value;

                $("#craneModalDialogContent").text("Note:Your request will be sent to site " + sitename + ".If you want to choose other sites,please click the [site] button on top right corner.Are you sure to add this service?ServiceName:" + servicename + ",Type:" + type);
                $('#craneModalDialog').dialog({
                    buttons: {
                        Confirm: function() {
                            $(this).dialog('close');

                            if (type == 'Java') {
                                typenum = 1;
                            }

                            else if (type == 'PHP') {
                                typenum = 0;
                            }

                            if (servicename == null) {
                                alert("Error!");
                            }
                            else if (pwd == '') {
                                var currentuser;
                                //$.post('/app/whoiam', {},
                                //function(serverResponse) {
                                currentuser = userid; //serverResponse.userid;
                                $.post('/' + sitename + '/webhosting/execute_wait/webapi.initDeploy.json', {
                                    serviceName: servicename,
                                    serviceType: typenum,
                                    userName: currentuser
                                },
                                function(serverResponse) {
                                    if (serverResponse == null) {

                                        alert("Deploy failed!");
                                        return 0;
                                    }
                                    else {
                                        serviceTableLength += 1;
                                        newService = servicename;
                                        $('#userWebHostingInfoTable').dataTable().fnAddData([
                                        sitename, servicename, type, 'deploying ...', 'deploying ...', 'deploying ...']);
                                    }
                                },
                                'json');
                                //	},
                                //	'json');
                            }

                            else if (pwd == pwd2) {

                                var currentuser;
                                //	$.post('/app/whoiam', {},
                                //	function(serverResponse) {
                                currentuser = userid; //serverResponse.userid;
                                $.post('/' + sitename + '/webhosting/execute_wait/webapi.initDeploy.json', {
                                    serviceName: servicename,
                                    serviceType: typenum,
                                    userName: currentuser,
                                    password: pwd
                                },
                                function(serverResponse) {
                                    if (serverResponse == null) {

                                        alert("Deploy failed!");
                                        return 0;
                                    }
                                    else {
                                        serviceTableLength += 1;
                                        newService = servicename;
                                        $("#userWebHostingPasswordField")[0].value = '';
                                        $("#userWebHostingPasswordConfirmField")[0].value = '';
                                        $('#userWebHostingInfoTable').dataTable().fnAddData([
                                        sitename, servicename, type, 'deploying ...', 'deploying ...', 'deploying ...']);
                                    }
                                },
                                'json');
                                //},
                                //'json');
                            }

                            else {
                                alert("Error!");
                            }
                        },
                        Cancel: function() {
                            $(this).dialog('close');
                        }
                    }
                }).dialog('open');
                $(this).dialog("close");

            },
            Cancel: function() {
                // var this_ = this;
                // window.setTimeout(function() {
                $(this).dialog("close");
                // },
                // 1000);
            }
        }
    });

    $('#userWebHostingServiceAddButton').click(function(event) {
        var currentuser;
        //var site=$("#preferredSiteComboBox")[0].value;
        // $.post('/app/whoiam', {},
        // function(serverResponse) {
        currentuser = userid; //serverResponse.userid;
        $.post('/webhosting/execute_wait/webapi.hasPass.json', {
            userName: currentuser
        },
        function(serverResponse) {
            if (serverResponse == true) {
                $("#userWebHostingPasswordField")[0].style.display = 'none';
                $("#userWebHostingPasswordConfirmField")[0].style.display = 'none';
                $("#userWebHostingPasswordText")[0].style.display = 'none';
                $("#userWebHostingPasswordConfirmText")[0].style.display = 'none';
            }

            else {

                $("#userWebHostingPasswordField")[0].style.display = 'inline';
                $("#userWebHostingPasswordConfirmField")[0].style.display = 'inline';
                $("#userWebHostingPasswordText")[0].style.display = 'inline';
                $("#userWebHostingPasswordConfirmText")[0].style.display = 'inline';

            }
            $('#userWebHostingAddServiceDialog').dialog('open');
        },
        'json');
        // },
        //'json');
    });

    $('#userWebHostingServiceRefreshButton').click(function() {

        var currentuser;
        //  $.post('/app/whoiam', {},
        //function(serverResponse) {
        currentuser = userid; //serverResponse.userid;
        for (var j = 0; j < allsites.length; j += 1) { (function(siteName) {
                $.post('/' + siteName + '/webhosting/execute_wait/webapi.serviceTableByUser.json', {
                    userName: currentuser
                },
                function(serverResponse) {
                    var servicename;
                    var servicetype;
                    var webftp;
                    var php;
                    var mysql;

                    for (var j = $('#userWebHostingInfoTable').dataTable().fnSettings().aoData.length - 1; j >= 0; j--) {
                        var name = $('#userWebHostingInfoTable').dataTable().fnSettings().aoData[j]._aData[0];
                        if (name == siteName) {
                            var node = $('#userWebHostingInfoTable').dataTable().fnGetNodes(j);
                            $('#userWebHostingInfoTable').dataTable().fnDeleteRow(node);
                        }
                    }

                    for (var i = 0; i < serverResponse.length; i += 1) {
                        servicename = serverResponse[i].serviceName;
                        servicetype = serverResponse[i].serviceType;
                        webftp = serverResponse[i].webftp;
                        php = serverResponse[i].phpMyAdmin;
                        mysql = serverResponse[i].mysql;
                        $('#userWebHostingInfoTable').dataTable().fnAddData([
                        siteName, servicename, servicetype, webftp, php, mysql]);
                        //console.log(serverResponse);
                        //console.log(serverResponse.length );
                        //  console.log(tnc );
                        //  console.log(inputfile );
                        //  console.log(command );
                        //  console.log(state );
                        //  console.log(result );
                    }
                },
                'json');
            })(allsites[j]);
        }
        // },
        // 'json');
    });

    $('#userWebHostingServiceQuotaButton').click(function() {
        var anSelected = fnGetSelected(userWebHostingInfoTable);
        var a = $('td', anSelected);
        if (a.length == 0) {
            alert("please select one row!");
            return 0;
        }

        location4Quota = $(a[0]).text();
        servicename4Quota = $(a[1]).text();

        var webuse, dbuse, webtotal, dbtotal, webusage, dbusage;
        var webindicator = document.getElementById("userWebHostingWebStorageCapacityIndicator");
        var dbindicator = document.getElementById("userWebHostingDBStorageCapacityIndicator");
        $.post('/' + location4Quota + '/webhosting/execute_wait/webapi.queryQuotaByService.json', {
            serviceName: servicename4Quota
        },
        function(serverResponse) {
            if (serverResponse == null) {
                alert("No Quota!");
            }

            else {
                webuse = serverResponse.webuse;
                dbuse = serverResponse.dbuse;
                webtotal = serverResponse.webtotal;
                dbtotal = serverResponse.dbtotal;
                webusage = serverResponse.webrate;
                dbusage = serverResponse.dbrate;
                //console.log(webusage);
                //console.log(dbusage);
                $("#userWebHostingWebStorageCapacityField")[0].value = webuse;
                $("#userWebHostingWebStorageUsedField")[0].value = webtotal;
                webindicator.object.setValue(webusage);
                $("#userWebHostingDBStorageCapacityField")[0].value = dbtotal;
                $("#userWebHostingDBStorageUsedField")[0].value = dbuse;
                dbindicator.object.setValue(dbusage);
            }
        },
        'json');
        $('#userWebHostingServiceDetailDialog').dialog('open');

    });

    var ajaxUserWebHostingUploadServiceFileFieldForm = new qq.FileUploader({
        element: $('#ajaxUserWebHostingUploadServiceFileFieldForm')[0],
        multiple: false,
        allowedExtensions: ['zip'],
        onComplete: function(id, fileName, responseJSON) {
            if (responseJSON.success) {
                serviceUploadedFiles.addObject(responseJSON.filename);
            }
        },
        action: '/storage/upload_tmpfile'
    });

    $('#userWebHostingUploadServiceDialog').dialog({
        autoOpen: false,
        modal: true,
        title: 'Upload Site Files',
        width: 450,
        buttons: {
            Confirm: function() {
                $(this).dialog('close');
                var splitFile, type;
                splitFile = serviceUploadedFiles[0].split('.');
                type = splitFile[splitFile.length - 1];
                if (type != 'zip') {
                    alert("Invalid Type Of File!");
                    return 0;
                }

                else {
                    $.post('/' + location4Upload + '/webhosting/execute_wait/webapi.upload.json', {
                        serviceName: servicename4Upload,
                        filePath: serviceUploadedFiles[0],
                    },
                    function(serverResponse) {
                        if (serverResponse == 0) {
                            alert("Succeeded!");
                        }

                        else {

                            alert("Failed!");

                        }
                        serviceUploadedFiles = [];
                    },
                    'json');
                }
                var ajaxUserWebHostingUploadServiceFileFieldForm = new qq.FileUploader({
                    element: $('#ajaxUserWebHostingUploadServiceFileFieldForm')[0],
                    multiple: false,
                    allowedExtensions: ['zip'],
                    onComplete: function(id, fileName, responseJSON) {
                        if (responseJSON.success) {
                            serviceUploadedFiles.addObject(responseJSON.filename);
                        }
                    },
                    action: '/storage/upload_tmpfile'
                });
            },

            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });

    $('#userWebHostingServiceUploadButton').click(function(event) {
        var anSelected = fnGetSelected(userWebHostingInfoTable);
        var a = $('td', anSelected);
        if (a.length == 0) {
            alert("please select one row!");
            return 0;
        }

        location4Upload = $(a[0]).text();
        servicename4Upload = $(a[1]).text();
        $('#userWebHostingUploadServiceDialog').dialog('open');
    });

    userWebHostingLoadInfoTable();

    //});
};
